<template>
<div :class="[$style.container]">
  <el-dialog title="设置" :visible.sync="visible" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" width="560px">
    <el-form size="small" label-position="top" :rules="rules" :model="form" @submit.native.prevent="" ref="fm">
      <el-form-item prop="api" label="文档服务地址">
        <el-input v-model="form.api" placeholder="例如：http://127.0.0.1:8001"></el-input>
      </el-form-item>
      <el-form-item prop="previewUrl" label="预览服务地址">
        <el-input v-model="form.previewUrl" placeholder="例如：http://127.0.0.1:8003"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button size="small" class="px-5" @click="onCancel">取 消</el-button>
      <el-button size="small" type="primary" class="px-5" @click="onConfirm">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script lang="ts">
import { getInitOptions, setInitOptions } from '@/config/init'
import { Vue, Component, Prop, Ref } from 'vue-property-decorator'

@Component
export default class Config extends Vue {
  @Ref() fm!: any

  visible = false

  form = {
    api: '',
    previewUrl: ''
  }

  rules = {
    api: [
      { required: true, message: '请输入文档服务地址', trigger: 'change' }
    ],
    previewUrl: [
      { required: true, message: '请输入预览服务地址', trigger: 'change' }
    ]
  }

  onCancel () {
    this.visible = false
    this.refresh()
  }

  onConfirm () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      setInitOptions(this.form)
      this.refresh()
    })
  }

  refresh () {
    localStorage.removeItem('jwt_token')
    localStorage.removeItem('token')
    this.$http.inst.defaults.baseURL = getInitOptions().api
    this.$router.push('/login')
  }

  created () {
    const c = getInitOptions()
    const params = {
      api: c?.api || '',
      previewUrl: c?.previewUrl || ''
    }
    Object.assign(this.form, params)
  }

  mounted () {
    this.visible = true
  }

  beforeDestroy () {
    this.visible = false
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {
  min-height: 100vh;
  background-color: #fff;
}
</style>
